package com.campusexpresspickup.config;

import com.campusexpresspickup.component.DynamicAccessDecisionManager;
import com.campusexpresspickup.component.DynamicSecurityMetadataSource;
import com.campusexpresspickup.component.DynamicSecurityService;
import com.campusexpresspickup.component.JwtAuthenticationTokenFilter;
import com.campusexpresspickup.component.RestAuthenticationEntryPoint;
import com.campusexpresspickup.component.RestfulAccessDeniedHandler;
import com.campusexpresspickup.entity.UserResource;
import com.campusexpresspickup.service.IOauthUserService;
import com.campusexpresspickup.service.IUserResourceService;
import com.campusexpresspickup.util.JwtTokenUtil;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class CampusExpressPickupSecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  private IOauthUserService oauthUserService;
  @Autowired
  private IUserResourceService resourceService;

  @Bean
  public UserDetailsService userDetailsService(){
    return username -> oauthUserService.loadUserByUsername(username);
  }

  @Bean
  public DynamicSecurityService dynamicSecurityService() {
    return () -> {
      Map<String, ConfigAttribute> map = new ConcurrentHashMap<>();
      List<UserResource> resourceList = resourceService.list();
      for (UserResource resource : resourceList) {
        map.put(resource.getUrl(), new SecurityConfig(
            resource.getId() + ":" + resource.getName()));
      }
      return map;
    };
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http
        .authorizeRequests();

    //允许所有请求
    registry.antMatchers("/**").permitAll();
    registry.and()
        .authorizeRequests()
        .anyRequest()
        .authenticated()
        .and()
        .csrf()
        .disable()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .exceptionHandling()
        .accessDeniedHandler(restfulAccessDeniedHandler())
        .authenticationEntryPoint(restAuthenticationEntryPoint())
        // 自定义权限拦截器JWT过滤器
        .and()
        .addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    //有动态权限配置时添加动态权限校验过滤器
//    if(dynamicSecurityService!=null){
//      registry.and().addFilterBefore(dynamicSecurityFilter(), FilterSecurityInterceptor.class);
//    }
  }

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
  }

  @Bean
  public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
  }

  //真实项目可根据需求配置白名单
  @Bean
  public IgnoreUrlsConfig ignoreUrlsConfig() {
    return new IgnoreUrlsConfig();
  }

  @Bean
  public JwtTokenUtil jwtTokenUtil() {
    return new JwtTokenUtil();
  }

  @Bean
  public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter() {
    return new JwtAuthenticationTokenFilter();
  }

  @Bean
  @Override
  public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
  }

  @Bean
  public RestAuthenticationEntryPoint restAuthenticationEntryPoint() {
    return new RestAuthenticationEntryPoint();
  }

  @Bean
  public RestfulAccessDeniedHandler restfulAccessDeniedHandler() {
    return new RestfulAccessDeniedHandler();
  }

  @ConditionalOnBean(name = "dynamicSecurityService")
  @Bean
  public DynamicAccessDecisionManager dynamicAccessDecisionManager() {
    return new DynamicAccessDecisionManager();
  }

//  @ConditionalOnBean(name = "dynamicSecurityService")
//  @Bean
//  public DynamicSecurityFilter dynamicSecurityFilter() {
//    return new DynamicSecurityFilter();
//  }

  @ConditionalOnBean(name = "dynamicSecurityService")
  @Bean
  public DynamicSecurityMetadataSource dynamicSecurityMetadataSource() {
    return new DynamicSecurityMetadataSource();
  }
}
